package com.useeinfo.oa.modules.base.dao;

import com.useeinfo.framework.extend.dao.CrudDao;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.QueryUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date: 2018/12/3 17:05
 * @Description: 企业Dao
 */
@Repository("enterpriseDao")
public class EnterpriseDao implements CrudDao<Enterprise> {

    private final static Logger logger = LoggerFactory.getLogger(EnterpriseDao.class);

    @PersistenceContext
    private EntityManager entityManager;


    @Override
    public Map<String, Object> getSearchCondition(Map<String, String> queryHash) {
        Map<String, Object> conditionHash = new HashMap<>();
        conditionHash.put("s.deleteStatus = ?{paramIndex} ", false);
        if (queryHash == null || queryHash.size() == 0) {
            return conditionHash;
        }

        String enterpriseName = queryHash.get("enterpriseName");
        if (StringUtils.isNotBlank(enterpriseName)) {
            conditionHash.put("enterpriseName like ?{paramIndex} ", "%" + enterpriseName + "%");
        }
        String code = queryHash.get("code");
        if (StringUtils.isNotBlank(code)) {
            conditionHash.put("code = ?{paramIndex} ", code);
        }
        String parentId = queryHash.get("parentId");
        if (StringUtils.isNotBlank(parentId)) {
            conditionHash.put("parentId = ?{paramIndex} ", StringConverters.null2Long(parentId));
        }
        String ancientId = queryHash.get("ancientId");
        if (StringUtils.isNotBlank(ancientId)) {
            conditionHash.put("parentIds like ?{paramIndex} ", "%,"+ancientId+",%");
        }
        String beforeCreateDate = queryHash.get("beforeCreateDate");
        if (StringUtils.isNotBlank(beforeCreateDate)) {
            conditionHash.put("createDate > ?{paramIndex} ", DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss",beforeCreateDate));
        }
        String magicLike = queryHash.get("magicLike");
        if (StringUtils.isNotBlank(magicLike)) {
            conditionHash.put("enterpriseName like ?{paramIndex} ", "%" + magicLike + "%");
        }
        String magicId = queryHash.get("magicId");
        if (StringUtils.isNotBlank(magicId)) {
            conditionHash.put("id != ?{paramIndex} ", StringConverters.ToLong(magicId));
        }
        String notFirstId = queryHash.get("notFirstId");
        if (StringUtils.isNotBlank(notFirstId)) {
            conditionHash.put("id != ?{paramIndex} ", StringConverters.ToLong(notFirstId));
        }
        String systemUserId = queryHash.get("systemUserId");
        if (StringUtils.isNotBlank(systemUserId)) {
            conditionHash.put("exists( select obj from s.systemUserSet obj where obj.id = ?{paramIndex})  ", StringConverters.ToLong(systemUserId));
        }
        return conditionHash;
    }

    @Override
    public Long totalRecord(Map<String, String> queryHash) {

        Map<String, Object> conditions = getSearchCondition(queryHash);
        TypedQuery<Long> typedQuery = QueryUtils.getTypedQueryByCondition("select count(s) from Enterprise s ", conditions, entityManager, Long.class);
        return typedQuery.getSingleResult();
    }

    @Override
    public List<Enterprise> findList(QueryParam queryParam) {
        String sqlInfo = queryParam.joinJPQL("select s from Enterprise s ", "order by s.id desc ");
        Map<String, Object> conditions = getSearchCondition(queryParam.getSqlMap());
        TypedQuery<Enterprise> typedQuery = QueryUtils.getTypedQueryByCondition(sqlInfo, conditions, entityManager, Enterprise.class);
        return queryParam.findPageList(typedQuery);
    }

    @Override
    public Enterprise findModel(Long userId) {
        return entityManager.find(Enterprise.class, userId);
    }

    @Override
    public Integer add(Enterprise enterprise) {
        enterprise.setCreateDate(new Date());
        entityManager.persist(enterprise);
        logger.info("EnterpriseDaoImpl添加enterprise成功！");
        return 1;
    }

    @Override
    public Integer update(Enterprise enterprise) {
        enterprise.setUpdateDate(new Date());
        entityManager.merge(enterprise);
        return 1;
    }

    @Override
    public Integer delete(Long enterpriseId) {
        Enterprise enterprise = entityManager.find(Enterprise.class, enterpriseId);
        entityManager.remove(enterprise);
        return 1;
    }

    @Override
    public Integer deleteLogic(Enterprise model) {
        model.setDeleteStatus(true);
        return 1;
    }

    /**
     * 删除企业所有的应用
     *
     * @param enterpriseId
     * @return
     */
    public synchronized Integer removeApplication(Long enterpriseId) {
        String sql = "DELETE FROM `enterprise_2_application` WHERE enterprise_id=" + enterpriseId;
        Query query = entityManager.createNativeQuery(sql);
        try {
            return query.executeUpdate();
        } catch (Exception ex) {
            return 0;
        }
    }

    /**
     * 获取企业选中的应用数据
     * @param enterpriseId
     * @return
     */
    public List getApplication(Long enterpriseId) {
        String sql = "SELECT application_id FROM `enterprise_2_application` WHERE enterprise_id="+enterpriseId;
        return entityManager.createNativeQuery(sql).getResultList();
    }


}
